#!/usr/bin/python
#
# Simple script to inhale a copy of the edit buffer for my aluminium
# gamer block and recalculate the various totals.
#

import sys
import re

def main():

  counter_names = [ "received", "played", "given", "traded" ]
  counter = dict(zip(counter_names, [0] * len(counter_names)))

  section = None;
  total_comment = ""
  errors = ""
  non_blank_seen = False
  for line in sys.stdin:
    print_line = True
    line = line.strip("\r\n")

    if line.startswith("[b]"):
      l = line.lower()
      l = l.split("(")[0]
      if l.find("received") > 0 or l.find("added") > 0:
        section = "received"
      elif l.find("traded") > 0 or l.find("sold") > 0:
        section = "traded"
      elif l.find("given") > 0 or l.find("gift") > 0:
        section = "given"
      elif l.find("played") > 0:
        section = "played"
      elif l.find("total") > 0:
        section = "total"
      else:
        section = ""
        errors += "Couldn't parse section " + line + "\n"
    elif not line.strip():
      if not non_blank_seen:
        print_line = False
      pass
    elif not section:
      pass
    elif line.startswith("[-]"):
      pass
    else:
      # handle comments in the total section which we'll be recreating
      # specially.
      if section == "total":
        print_line = False
        m = re.search("\((.+)\)", line)
        if m:
          total_comment += m.group(1)
      else:
        counter[section] += 1

    if print_line:
      non_blank_seen = True
      print line

  total = (-counter["received"] + counter["played"] + 3 * counter["given"] +
           counter["traded"])
  print "%d received vs %d played + 3 * %d given away + %d traded/sold" % (
    counter["received"],
    counter["played"],
    counter["given"],
    counter["traded"])
  if total_comment:
    print "Total: %d (%s)" % (total, total_comment)
  else:
    print "Total: %d" % total

  if errors:
    print
    print errors


if __name__ == "__main__":
  main()
